package com.alibaba.cloud.client9093.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import sun.security.util.Debug;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * created by wuquan at 05/09/2021
 * ^_^ ^_^  根据BlockException  判断是流控，还是降级还是授权限制。。。
 */
@Component
@Slf4j
public class MyGlobalBlockHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {

        httpServletResponse.setStatus(500);
        httpServletResponse.setCharacterEncoding("UTF-8");


        httpServletResponse.setHeader("Content-Type","application/json;character=utf-8");

        JSONObject j = new JSONObject();

        if (e instanceof FlowException) {
            j.put("error_code", 1);
        } else if (e instanceof DegradeException) {
            j.put("error_code", 1);
        } else if (e instanceof ParamFlowException) {
            j.put("error_code", 1);
        } else j.put("error_code", 99);
        //log.info(JSONObject.toJSONString(httpServletResponse));
        httpServletResponse.getWriter().write(j.toJSONString());


    }
}
